package com.zc.controller.oldStore;

import com.zc.dto.ResultDto;
import com.zc.entity.Image;
import com.zc.service.lightbox.LightboxServer;
import com.zc.utils.Contants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.PrintWriter;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/lightbox")
public class LightboxController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Resource
    private LightboxServer biz;

    @RequestMapping("/preAdd")
    public String preAdd() {
        return "addPicture";
    }

    @RequestMapping("/save")
    public String save(Image img, Model model) {
        ResultDto<String> result = new ResultDto<>();
        try {
            img.setState(0);
            biz.save(img);
            result.setMessage("保存成功");
            result.setSuccess(true);
        } catch (Exception e) {
            result.setMessage("保存失败");
            result.setSuccess(false);
            logger.debug("imgSave Error::,{}", e);
        }
        //带有参数的方法跳转
        return "redirect:findAll?state=0";
    }
    @RequestMapping("/findAll")
    public String findAll(Model model, int state, HttpServletRequest request){
        List<Image> imgList = biz.findAll(state);
        //model.addAttribute("list",imgList);
        request.getSession(false).setAttribute("list",imgList);
        return "pictureShow";
    }
    @RequestMapping("/upload")
    public void upload(MultipartHttpServletRequest request, PrintWriter out){
        try {
            MultipartFile file = request.getFile("upload");
            String fileName = UUID.randomUUID().toString();
            File newFile = new File(Contants.IMAGE_PATH + fileName);
            file.transferTo(newFile);
            String callback = request.getParameter("CKEditorFuncNum");
            out.println("<script type=\"text/javascript\">");
            out.println("window.parent.CKEDITOR.tools.callFunction("+ callback + ",'" +
                    request.getContextPath() + "/show/"+ fileName + "','')");
            out.println("</script>");
        }
        catch (Exception e) {
            e.printStackTrace();
            logger.error("e:,{}",e);
        }
    }

}
